package com.itheima.service;

import com.itheima.common.SnowFlake;
import com.itheima.mapper.client.AddressBookMapper;
import com.itheima.pojo.client.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


/**
 * @author ChenJunJie
 * @date 2022/6/18 17:23
 * 收货地址service层
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AddressBookService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private AddressBookMapper addressBookMapper;

    //新增地址
    public boolean addAddress(AddressAddDto addressAdd) {

        //设置地址id
        long id = snowFlake.nextId();
        addressAdd.setId(id + "");

        int i = addressBookMapper.addAddress(addressAdd);

        return i > 0;
    }

    //通过userid查询所有地址
    public List<SelectAddressVo> selectAddress(String userId) {
        return addressBookMapper.selectAddress(userId);
    }

    //设置默认收货地址
    public SelectDefaultAddressVo updateDefaultAddress(UpdateDefaultAddressDto defaultAddressDto) {

        //先将所有的地址均改成普通地址
        addressBookMapper.updateNotDefaultAddress();

        //将需要修改的地址改成默认地址
        addressBookMapper.updateDefaultAddress(defaultAddressDto);

        //查询默认收货地址
        return addressBookMapper.selectDefaultAddress();

    }

    //获取默认收货地址
    public SelectDefaultAddressVo selectDefaultAddress() {

        //查询默认收货地址
        return addressBookMapper.selectDefaultAddress();
    }

    //根据id获取收货地址
    public SelectAddressByIdVo selectAddressById(String id) {

        return addressBookMapper.selectAddressById(id);
    }

    //修改收货地址
    public boolean updateAddressById(UpdateAddressByIdDto updateAddressById) {
        int i = addressBookMapper.updateAddressById(updateAddressById);
        return i > 0;
    }

    //删除收货地址
    public boolean deleteAddressById(@Param("id") String id) {
        int i = addressBookMapper.deleteAddressById(id);
        return i > 0;
    }


}
